<?php

namespace app\wechat\service;

use app\admin\service\BaseService;
use app\wechat\model\ApplicationModel;
use app\wechat\model\OfficeMessageModel;
use app\wechat\model\OfficeQrcodeModel;
use app\wechat\model\OfficeTemplateModel;
use app\wechat\model\OfficeTemplateSendRecordModel;
use EasyWeChat\Factory;
use Exception;
use think\facade\App;

/**
 * 公众号服务类
 *
 * @Author tanruizheng
 * @DateTime 2021-08-17
 */
class OfficeService extends BaseService
{
    public $app;
    public $appId;

    /**
     * app实例
     *
     * @Author tanruizheng
     * @DateTime 2021-08-10
     * @return object
     */
    public function getApp(){
        return $this->app;
    }

    public function __construct($appId)
    {
        $application = ApplicationModel::where(
            [
                'app_id'        => $appId,
                'account_type'  => ApplicationModel::ACCOUNT_TYPE_OFFICE
            ]
        )->findOrEmpty()->toArray();
        if(empty($application)){
           throw new Exception('应用信息不存在');
        }
        $config = [
            'app_id' => $application['app_id'],
            'secret' => $application['secret'],
        ];
        $this->appId = $appId;
        $this->app = Factory::officialAccount($config);
    }

    /**
     * 获取所有模板列表
     *
     * @Author tanruizheng
     * @DateTime 2021-08-20
     * @return void
     */
    public function getPrivateTemplates(){
        $res = $this->getApp()->template_message->getPrivateTemplates();
        if(isset($res['template_list']) && $res['template_list']){
            $templateList = $res['template_list'];
            foreach ($templateList as $item) {
                $templateId = $item['template_id'];
                $OfficeTemplateModel = OfficeTemplateModel::where('template_id',$templateId)->findOrEmpty();
                $OfficeTemplateModel->app_id = $this->appId;
                $OfficeTemplateModel->template_id = $templateId;
                $OfficeTemplateModel->title = $item['title'];
                $OfficeTemplateModel->example = $item['example'];
                $OfficeTemplateModel->content = $item['content'];
                $OfficeTemplateModel->primary_industry = $item['primary_industry'];
                $OfficeTemplateModel->deputy_industry = $item['deputy_industry'];
                $OfficeTemplateModel->save();
            }
            return self::createSuccess('获取成功');
        }else{
            return self::createFail('获取失败');
        }
    }

    /**
     * 发送模板消息
     *
     * @Author tanruizheng
     * @DateTime 2021-08-20
     * @return void
     */
    public function sendTemplateMessage($openId, $templateId,$data = [], $url ='', $miniprogram = []){
        $postData = [
            'touser'        => $openId,
            'template_id'   => $templateId,
            'url'           => $url,
            'miniprogram'   => $miniprogram,
            'data'          => $data,
        ];
        $res = $this->getApp()->template_message->send($postData);

        $OfficeTemplateSendRecordModel = new OfficeTemplateSendRecordModel();
        $OfficeTemplateSendRecordModel->app_id = $this->appId;
        $OfficeTemplateSendRecordModel->open_id = $openId;
        $OfficeTemplateSendRecordModel->template_id = $templateId;
        $OfficeTemplateSendRecordModel->url = $url;
        $OfficeTemplateSendRecordModel->miniprogram = json_encode($miniprogram);
        $OfficeTemplateSendRecordModel->post_data = json_encode($postData);
        $OfficeTemplateSendRecordModel->result = json_encode($res);
        $OfficeTemplateSendRecordModel->save();
        
        if($res['errcode'] == 0){
            $OfficeTemplateSendRecordModel->result = '发送成功';
            $OfficeTemplateSendRecordModel->save();
            return true;
        }else{
            $OfficeTemplateSendRecordModel->result = $res['errmsg'];
            $OfficeTemplateSendRecordModel->save();
            $this->setError($res['errmsg']);
            return false;
        }
    }

    /**
     * 创建临时二维码
     *
     * @Author tanruizheng
     * @DateTime 2021-08-20
     * @return void
     */
    public function createTemporaryQrcode($param, $expireTime){
        $res = $this->getApp()->qrcode->temporary($param, $expireTime);
        if(!empty($res['ticket'])){
            $ticket = $res['ticket'];
            $url = $this->getApp()->qrcode->url($ticket);
            $content = file_get_contents($url); // 得到二进制图片内容
            $qrcodeDir = App::getRootPath() . '/public/d/wechat/qrcode';
            if(!is_dir($qrcodeDir)){
                mkdir($qrcodeDir, 0755, true);
            }
            $fileName = time() . rand(10000,99999).'.png';
            $filePath = $qrcodeDir . '/'. $fileName;
            $saveRes = file_put_contents($filePath, $content);
            if($saveRes){
                $expireTime = time() + $expireTime;
                $qrcodeUrl = request()->domain() . '/d/wechat/qrcode/' . $fileName;
                $officeQrcodeModel = new OfficeQrcodeModel();
                $officeQrcodeModel->app_id = $this->appId;
                $officeQrcodeModel->param = $param;
                $officeQrcodeModel->expire_time = $expireTime;
                $officeQrcodeModel->type = OfficeQrcodeModel::QRCODE_TYPE_TEMPORARY;
                $officeQrcodeModel->file_path = $filePath;
                $officeQrcodeModel->qrcode_url = $qrcodeUrl;
                $officeQrcodeModel->save();
                return self::createSuccess('获取二维码成功',[
                    'qrcode_url' => $qrcodeUrl,
                    'expire_time' => $expireTime
                ]);
            }else{
                return self::createFail('保存二维码失败');
            }
        }else{
            return self::createFail('获取失败');
        }
    }

    /**
     * 创建永久二维码
     *
     * @Author tanruizheng
     * @DateTime 2021-08-20
     * @return void
     */
    public function createForverQrcode($param){
        $res = $this->getApp()->qrcode->forever($param);
        if(!empty($res['ticket'])){
            $ticket = $res['ticket'];
            $url = $this->getApp()->qrcode->url($ticket);
            $content = file_get_contents($url); // 得到二进制图片内容
            $qrcodeDir = App::getRootPath() . '/public/d/wechat/qrcode';
            if(!is_dir($qrcodeDir)){
                mkdir($qrcodeDir, 0755, true);
            }
            $fileName = time() . rand(10000,99999).'.png';
            $filePath = $qrcodeDir . '/'. $fileName;
            $saveRes = file_put_contents($filePath, $content);
            if($saveRes){
                $qrcodeUrl = request()->domain() . '/d/wechat/qrcode/' . $fileName;
                $officeQrcodeModel = new OfficeQrcodeModel();
                $officeQrcodeModel->app_id = $this->appId;
                $officeQrcodeModel->param = $param;
                $officeQrcodeModel->expire_time = 0;
                $officeQrcodeModel->type = OfficeQrcodeModel::QRCODE_TYPE_FORVER;
                $officeQrcodeModel->file_path = $filePath;
                $officeQrcodeModel->qrcode_url = $qrcodeUrl;
                $officeQrcodeModel->save();
                return self::createSuccess('获取二维码成功',[
                    'qrcode_url' => $qrcodeUrl,
                ]);
            }else{
                return self::createFail('保存二维码失败');
            }
        }else{
            return self::createFail('获取失败');
        }
    }

    /**
     * 处理普通消息
     *
     * @Author tanruizheng
     * @DateTime 2021-08-23
     * @return void
     */
    public function handleMessage($message){
        $OfficeMessageModel = new OfficeMessageModel();
        $OfficeMessageModel->app_id = $this->appId;
        $OfficeMessageModel->to_user_name = $message['ToUserName'];
        $OfficeMessageModel->from_user_name = $message['FromUserName'];
        $OfficeMessageModel->create_time = $message['CreateTime'];
        $OfficeMessageModel->msg_type = $message['MsgType'];
        $OfficeMessageModel->msg_id = $message['MsgId'];
        $OfficeMessageModel->content = isset($message['Content']) ? $message['Content'] : '';
        $OfficeMessageModel->pic_url = isset($message['PicUrl']) ? $message['PicUrl'] : '';
        $OfficeMessageModel->media_id = isset($message['MediaId']) ? $message['MediaId'] : '';
        $OfficeMessageModel->format = isset($message['Format']) ? $message['Format'] : '';
        $OfficeMessageModel->recognition = isset($message['Recognition']) ? $message['Recognition'] : '';
        $OfficeMessageModel->thumb_media_id = isset($message['ThumbMediaId']) ? $message['ThumbMediaId'] : '';
        $OfficeMessageModel->location_x = isset($message['Location_X']) ? $message['Location_X'] : '';
        $OfficeMessageModel->location_y = isset($message['Location_Y']) ? $message['Location_Y'] : '';
        $OfficeMessageModel->scale = isset($message['Scale']) ? $message['Scale'] : '';
        $OfficeMessageModel->label = isset($message['Label']) ? $message['Label'] : '';
        $OfficeMessageModel->title = isset($message['Title']) ? $message['Title'] : '';
        $OfficeMessageModel->description = isset($message['Description']) ? $message['Description'] : '';
        $OfficeMessageModel->url = isset($message['Url']) ? $message['Url'] : '';
        $res = $OfficeMessageModel->save();
        return $res;
    }
}